<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基础" name="base">
        <form-admin
          :id="id"
          v-model="mainForm"
          entity-conf="Product"
          :fields="formFields"
        >
          <template v-slot:action="{ submit, form }">
            <el-button
              type="primary"
              icon="el-icon-edit-outline"
              @click="
                Object.assign(form, attachmentForm)
                submit(formSubmit)
              "
            >
              保存
            </el-button>
          </template>
        </form-admin>
      </el-tab-pane>

      <el-tab-pane label="规格" name="specification">
        <template v-if="!id">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="mainForm['specifications'].push({})"
          >
            增加
          </el-button>
          <div
            v-for="(specification, index) in mainForm['specifications']"
            :key="index"
          >
            <form-admin
              v-model="mainForm['specifications'][index]"
              entity-conf="Specification"
              :fields="[...specificationFormFields.filter(
                (v, k) =>
                  ['price'].includes(v) ||
                  ['name'].includes(v.property)
              )
              ]"
            >
              <template v-slot:action><span /></template>
            </form-admin>
            <p circle style="text-align: right">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="mainForm['specifications'].splice(index, 1)"
              />
            </p>
          </div>
        </template>

        <template v-else>
          <list-admin
            :key="specificationRefreshKey"
            entity-conf="Specification"
            :list-display="specificationListDisplay"
            :list-filter="specificationListFilter"
            :query="{
              '@filter': `entity.getProduct().getId() == ${Number(
                $route.params.id
              )}`,
            }"
          >
            <template v-slot:topButton>
              <el-button
                size="medium"
                type="primary"
                icon="el-icon-plus"
                plain
                @click="
                  specificationId = null
                  dialogRefreshKey++
                  dialogShow = true
                "
              >
                新增
              </el-button>
            </template>

            <template v-slot:action:edit="{ data }">
              <el-button
                size="small"
                icon="el-icon-edit"
                plain
                @click="
                  specificationId = data.id
                  dialogRefreshKey++
                  dialogShow = true
                "
              >
                修改
              </el-button>
            </template>
          </list-admin>

          <el-dialog
            :title="specificationId ? '更新' : '新增'"
            :visible.sync="dialogShow"
            width="40%"
            align="left"
            :before-close="
              (done) => {
                specificationForm = { product: $route.params.id }
                done()
              }
            "
          >
            <form-admin
              :id="specificationId"
              :key="dialogRefreshKey"
              v-model="specificationForm"
              entity-conf="Specification"
              :fields="specificationFormFields"
            >
              <template v-slot:action="{ submit }">
                <el-button
                  type="primary"
                  icon="el-icon-edit-outline"
                  @click="
                    submit(() => {
                      $message({
                        message: `${specificationId ? '更新' : '新增'}成功`,
                        type: 'success',
                      })

                      // refresh specification list component
                      specificationRefreshKey++
                      dialogShow = false

                      // clear form content
                      specificationForm = { product: $route.params.id }
                    })
                  "
                >
                  保存
                </el-button>
              </template>
            </form-admin>
          </el-dialog>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import FormAdmin from '@/components/EasyAdmin/FormAdmin'
import ListAdmin from '@/components/EasyAdmin/ListAdmin'
import admin from '@/config'

export default {
  components: { FormAdmin, ListAdmin },
  data() {
    return {
      mainForm: {
        specifications: []
      },
      attachmentForm: {},
      specificationForm: { product: this.$route.params.id },

      id: Number(this.$route.params.id),
      activeName: 'base',
      formFields: admin.entities['Product'].form.fields,
      specificationFormFields: admin.entities['Specification'].form.fields,
      specificationListDisplay:
        admin.entities['Specification'].list.list_display,
      specificationListFilter:
        admin.entities['Specification'].list.list_filter,
      specificationRefreshKey: 0,

      // dialog
      dialogShow: false,
      dialogRefreshKey: 0,
      specificationId: null
    }
  },
  methods: {
    async formSubmit(response) {
      // 新增 product 默认新增 store-product
      // if (!this.id) {
      //   const waitPromise = []
      //   this.axios.get('/manage/stores').then((res) => {
      //     res.data.forEach((e) => {
      //       waitPromise.push(
      //         this.axios.post('/manage/store-products', {
      //           store: e.id,
      //           product: response.data.id,
      //           isOnSale: response.data.isOnSale
      //         })
      //       )
      //     })
      //   })
      //   await Promise.all(waitPromise)
      // }
      this.$message({ message: '保存成功', type: 'success' })
    }
  }
}
</script>
